package com.javaweb.dao.impl;

import com.javaweb.dao.ArticleDao;
import com.javaweb.dao.CommentDao;
import com.javaweb.model.Article;
import com.javaweb.model.Comment;
import com.javaweb.model.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;

@Repository
public class CommentDaoImpl implements CommentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Comment newComment) {
        String sql = "INSERT INTO tb_comment (article_id, user_id, content, create_time, support, oppose) VALUES (?, ?, ?, ?, 0, 0)";
        int result = jdbcTemplate.update(sql, newComment.getArticleId(), newComment.getUserId(), newComment.getContent(), newComment.getCreateTime());
        return result == 1 ? 1 : 0;
    }

    @Override
    public int insertSupport(Integer commentId) {
        String sql = "UPDATE tb_comment SET support = support + 1 WHERE id = ?";
        int result = jdbcTemplate.update(sql, commentId);
        return result == 1 ? 1 : 0;
    }

    @Override
    public int insertOppose(Integer commentId) {
        String sql = "UPDATE tb_comment SET oppose = oppose + 1 WHERE id = ?";
        int result = jdbcTemplate.update(sql, commentId);
        return result == 1 ? 1 : 0;
    }

    @Override
    public List<Comment> selectAllCommentsById(Integer articleId) {
        String sql = "SELECT * FROM tb_comment WHERE article_id = ? ORDER BY create_time DESC";
        List<Comment> comments = jdbcTemplate.query(sql, new Object[]{articleId}, new BeanPropertyRowMapper<>(Comment.class));
        return comments.isEmpty() ? null : comments;
    }
}
